<template>
  <div style="margin-bottom: 20px">
    <div class="user-profile">
      <div class="box-center">
        <pan-thumb
          :image="fullAvatarUrl"
          :height="'100px'"
          :width="'100px'"
          :hoverable="false"
        >
          <div>Hello</div>
          {{ username }}
        </pan-thumb>
      </div>
      <div class="box-action">
        <i class="el-icon-edit" style="color: #000" @click="changeAvatar"></i>
      </div>
    </div>

    <div class="user-bio">
      <!-- <div>
        <div class="user-name text-center">{{ user.name }}</div>
        <div class="user-role text-center text-muted">
          {{ user.role | uppercaseFirst }}
        </div>
      </div> -->
      <div class="user-education user-bio-section">
        <div class="user-bio-section-header">
          <svg-icon icon-class="education" /><span>个人资料</span>
        </div>
        <div class="user-bio-section-body">
          <div class="user-bio-section-body-item">
            <div><svg-icon icon-class="person" />登录名称:</div>
            <div>{{ username }}</div>
          </div>
          <div class="user-bio-section-body-item">
            <div><svg-icon icon-class="mobile" />手机号码:</div>
            <div>{{ phonenumber }}</div>
          </div>
          <div class="user-bio-section-body-item">
            <div><svg-icon icon-class="business" />所属企业:</div>
            <div>{{ userInfo.userInfo.departName }}</div>
          </div>
          <div class="user-bio-section-body-item">
            <div><svg-icon icon-class="mail" />邮箱地址:</div>
            <div>{{ email }}</div>
          </div>
          <div class="user-bio-section-body-item">
            <div><svg-icon icon-class="createTime" />创建时间:</div>
            <div>{{ userInfo.userInfo.createTime }}</div>
          </div>
        </div>
      </div>

      <div class="user-skills user-bio-section"></div>
    </div>
    <el-dialog
      title="更换头像"
      :visible.sync="dialogVisible"
      width="850px"
      @close="handleDialogClose"
    >
      <UpdateAvater
        ref="updateAvater"
        :avatar="fullAvatarUrl"
        :confirmBtn="confirmBtn"
        @updateAvatar="updateAvatarConfirm"
      ></UpdateAvater>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleDialogClose">取 消</el-button>
        <el-button type="primary" @click="comfirmAvatar">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import PanThumb from "@/components/PanThumb";
import UpdateAvater from "./UpdateAvater.vue";
import { updateAvatar } from "@/api/user";

export default {
  components: { PanThumb, UpdateAvater },
  data() {
    return {
      dialogVisible: false,
      userInfo: {},
      confirmBtn: false,
    };
  },
  props: {
    user: {
      type: Object,
      default: () => {
        return {
          name: "",
          email: "",
          avatar: "",
          role: "",
          userInfo: {},
        };
      },
    },
  },
  watch: {
    user: {
      handler(val) {
        this.userInfo = val;
      },
      immediate: true,
      deep: true,
    },
  },
  computed: {
    fullAvatarUrl() {
      // 处理头像 URL，如果 avatar 不存在则使用默认头像
      if (!this.avatar) {
        return "https://dn.xinnuanyun.com/suittc_dn/profile/avatar/2025/11/04/ec37f056-1975-467c-81c4-d991f13b3668.png"; // 使用默认头像
      }
      // 如果 avatar 是完整 URL，则直接使用
      if (this.avatar.startsWith("http")) {
        return this.avatar;
      }
      // 否则拼接基础 URL
      return `${process.env.VUE_APP_BASE_API}${this.avatar}`;
    },
    username() {
      return this.$store.state.user.username;
    },
    phonenumber() {
      return this.$store.state.user.userInfo.phonenumber;
    },
    email() {
      return this.$store.state.user.userInfo.email;
    },
    avatar() {
      return this.$store.state.user.userInfo.avatar;
    }
  },
  methods: {
    changeAvatar() {
      this.dialogVisible = true;
    },
    comfirmAvatar() {
      this.confirmBtn = true;
    },
    handleDialogClose() {
      this.dialogVisible = false;
      // 重置状态
      this.confirmBtn = false;
      setTimeout(() => {
        if (this.$refs.updateAvater) {
          this.$refs.updateAvater.resetCropperState();
        }
      }, 100);
    },
    updateAvatarConfirm(val) {
      this.base64ToFile(val, "avatar.png", "image/png")
        .then((file) => {
          // 创建 FormData 对象并上传
          this.uploadAvatarFile(file);
        })
        .catch((error) => {
          console.error("转换失败:", error);
          this.$message.error("图片转换失败");
        });
    },
    // 将 base64 字符串转换为 File 对象
    base64ToFile(base64String, filename, mimeType) {
      return new Promise((resolve, reject) => {
        try {
          // 移除 base64 前缀
          const base64Data = base64String.replace(
            /^data:image\/\w+;base64,/,
            ""
          );

          // 将 base64 转换为二进制数据
          const byteString = atob(base64Data);
          const ab = new ArrayBuffer(byteString.length);
          const ia = new Uint8Array(ab);

          for (let i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
          }

          // 创建 File 对象
          const file = new File([ab], filename, { type: mimeType });
          resolve(file);
        } catch (error) {
          reject(error);
        }
      });
    },
    // 上传头像文件
    uploadAvatarFile(file) {
      // 创建 FormData 对象
      const formData = new FormData();
      formData.append("avatarfile", file);

      // 验证 FormData 构建是否正确
      // console.log("FormData 内容:");
      // for (let [key, value] of formData.entries()) {
      //   console.log(key, value);
      //   if (value instanceof File) {
      //     console.log(
      //       `文件名: ${value.name}, 大小: ${value.size} bytes, 类型: ${value.type}`
      //     );
      //   }
      // }

      // 调用上传接口
      updateAvatar(formData)
        .then((res) => {
          if (res.code === 0) {
            // 注意：应该是 0 而不是 200
            this.$message.success("头像修改成功");
            // 更新 Vuex 中的头像信息
            if (res.data) {
              this.$store.commit("user/SET_AVATAR", res.data.avatar);
            }
          }
        })
        .finally(() => {
          this.dialogVisible = false;
          this.confirmBtn = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.box-center {
  margin: 0 auto;
  display: table;
}

.text-muted {
  color: #777;
}

.user-profile {
  width: 400px;
  position: relative;
  .box-action {
    width: 30px;
    height: 30px;
    border-radius: 50%;
    background-color: rgba(255, 255, 255, 0.7);
    display: flex;
    justify-content: center;
    align-items: center;
    position: absolute;
    top: 82px;
    right: 145px;
    z-index: 999;
  }
}
.user-name {
  font-weight: bold;
}

.box-center {
  padding-top: 10px;
}

.user-role {
  padding-top: 10px;
  font-weight: 400;
  font-size: 14px;
}

.box-social {
  padding-top: 30px;

  .el-table {
    border-top: 1px solid #dfe6ec;
  }
}

.user-follow {
  padding-top: 20px;
}
.user-bio {
  margin-top: -50px;
  padding-top: 50px;
  color: #606266;
  background: linear-gradient(#75a4f4, #deecff);
  border-radius: 10px;

  span {
    padding-left: 4px;
  }

  .user-bio-section {
    font-size: 14px;
    padding: 15px;

    .user-bio-section-header {
      border-bottom: 1px solid #dfe6ec;
      padding-bottom: 10px;
      margin-bottom: 10px;
      font-weight: bold;
      color: #1c1b1b;
    }
    .user-bio-section-body {
      margin-top: 15px;
      .user-bio-section-body-item {
        display: flex;
        justify-content: space-between;
        padding: 12px 15px;
        background-color: #fff;
        border-radius: 5px;
        margin-bottom: 10px;
        .svg-icon {
          margin-right: 5px;
        }
      }
    }
  }
}
</style>
